const Router = require('@koa/router');
const fileUtils = require('./fileUtils');

// 创建路由实例
const router = new Router();

// 初始数据API路由
router.get('/api/initial-data', async (ctx) => {
    try {
        const [
            airQuality,
            pollutionRanking,
            temperatureHumidity,
            waterQuality,
            energyConsumption,
            monitoringStations,
            overviewStats
        ] = await Promise.all([
            fileUtils.readDataFile('airQuality'),
            fileUtils.readDataFile('pollutionRanking'),
            fileUtils.readDataFile('temperatureHumidity'),
            fileUtils.readDataFile('waterQuality'),
            fileUtils.readDataFile('energyConsumption'),
            fileUtils.readDataFile('monitoringStations'),
            fileUtils.readDataFile('overviewStats')
        ]);

        ctx.body = {
            airQuality,
            pollutionRanking,
            temperatureHumidity,
            waterQuality,
            energyConsumption,
            monitoringStations,
            overviewStats
        };
    } catch (error) {
        console.error('获取初始数据失败:', error);
        ctx.status = 500;
        ctx.body = { error: '获取数据失败' };
    }
});

// 单个数据类型API路由
router.get('/api/:dataType', async (ctx) => {
    try {
        const { dataType } = ctx.params;
        const fileKey = convertToFileKey(dataType);

        if (!fileKey) {
            ctx.status = 400;
            ctx.body = { error: '无效的数据类型' };
            return;
        }

        const data = await fileUtils.readDataFile(fileKey);
        ctx.body = { [dataType]: data };
    } catch (error) {
        console.error(`获取${ctx.params.dataType}数据失败:`, error);
        ctx.status = 500;
        ctx.body = { error: '获取数据失败' };
    }
});

// 辅助函数：将URL参数转换为文件键
function convertToFileKey(dataType) {
    const mapping = {
        'air-quality': 'airQuality',
        'pollution-ranking': 'pollutionRanking',
        'temperature-humidity': 'temperatureHumidity',
        'water-quality': 'waterQuality',
        'energy-consumption': 'energyConsumption',
        'monitoring-stations': 'monitoringStations',
        'overview-stats': 'overviewStats'
    };

    return mapping[dataType] || null;
}

module.exports = router;